package com.jiuyou.storeController.staff;/**
 * @Title:staffController
 * @ClassName: ruoyi
 * @Description: TODO
 * @author: java
 * @time: 2024/2/29 17:00
 */

import com.alibaba.fastjson.JSONObject;
import com.jiuyou.storeController.common.StoreBaseController;
import com.ruoyi.adapayBalance.domain.AdapayBalance;
import com.ruoyi.clerkBalance.domain.ClerkBalance;
import com.ruoyi.clerkBalance.service.IClerkBalanceService;
import com.ruoyi.clerkBalanceRecord.domain.ClerkBalanceRecord;
import com.ruoyi.clerkBalanceRecord.service.IClerkBalanceRecordService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.StoreUserRole;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.aes.AESCipher;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.shopping.domain.BbsLike;
import com.ruoyi.staff.domain.Staff;
import com.ruoyi.staff.service.IStaffService;
import com.ruoyi.store.domain.Store;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.wechat.util.CommonUtil;
import com.ruoyi.wechat.util.ConstantWeChat;
import com.ruoyi.wechat.util.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import org.jasypt.encryption.StringEncryptor;


/**
 * @ClassName: staffController
 * @Description: TODO
 * @author: java
 * @time: 2024/2/29 17:00
 */
@RestController
@RequestMapping("/store/staff")
@Api(tags = {"员工信息控制器"})
public class staffInfoController extends StoreBaseController {

    @Autowired
    private IStaffService staffService;
    @Autowired
    private IClerkBalanceService clerkBalanceService ;
    @Autowired
    StringEncryptor stringEncryptor;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private CommonUtil commonUtil;
    @Autowired
    private IClerkBalanceRecordService clerkBalanceRecordService;


    @PostMapping("/add")
    @ApiOperation("添加员工")
    public AjaxResult create(@ApiParam @RequestBody Staff staff) throws Exception {
        StoreUserRole role = getStoreUserRole();
        if (role == null) {
            throw new CustomException("权限不足");
        }
        if(StringUtils.isEmpty(staff.getPhone()))
        {
            throw new CustomException("手机号必填");
        }
        //新增时校验这个手机号是否已经存在，存在的话不让添加
        Staff staff1=new Staff();
        staff1.setPhone(staff.getPhone());
        List<Staff> list=staffService.selectStaffList(staff1);
        if(list.size()>0) {
            throw new CustomException("手机号" + staff.getPhone() + "已存在");
        }
        staff.setUserType("2");
        staff.setStoreId(role.getStoreId());
        staff.setState(DicConstants.SYS_Y.getCode());
        staff.setCreateBy(getLoginStoreUserId());
        staff.setCreateType(DicConstants.BUSINESS_Business.getCode());
        String random = "818W38q62e6OcC87";
        byte[] aesKey = random.getBytes();
        String pwd = AESCipher.encrypt(aesKey,staff.getPassword());
        staff.setPassword(pwd);
//        String decryptText = AESCipher.decrypt(aesKey, pwd);
//        System.out.println("解密后:\n" + decryptText);

        Integer res = staffService.insertStaff(staff);
        Long storeUserId = staff.getId();
        if(null==clerkBalanceService.getClerkBalanceByStoreUserId(storeUserId)){
            ClerkBalance clerkBalance=new ClerkBalance();
            clerkBalance.setStoreId(role.getStoreId());
            clerkBalance.setStoreUserId(storeUserId);
            clerkBalanceService.insertClerkBalance(clerkBalance);
        }
        //产生绑定下级二维码
        storeBelow(storeUserId);//绑定为下级二维码
        return AjaxResult.success(res);
    }

    public String storeBelow(Long storeUserId){
//        if(null==storeUserId){
//            StoreUserRole storeUserRole=getStoreUserRole();
//            storeId= storeUserRole.getStoreId();
//        }
        Staff staff = staffService.selectStaffById(storeUserId);
        //Store store=storeService.selectStoreById(storeUserId);
        String belowImageUrl=staff.getBelowImageUrl();
        if(!StringUtils.isEmpty(belowImageUrl)){
            return belowImageUrl;
        }
        //long userId = getLoginStoreUserId();
        String APPKEY="YQS_C";
        String requrl= serverConfig.getUrl();
        JSONObject param=new JSONObject();
        String qrcodePage="";
        String scene="";
        String page="";
        //图书，进入章节目录
        scene="storeUserId="+storeUserId;
        page="pages/UCenter/index/index";
        param.put("scene",scene);
        param.put("page",page);
        qrcodePage=page+"?"+scene;
        String pro_env=sysConfigService.selectConfigByKey(DicConstants.PRO_ENV.getCode());
        if(null==pro_env){
            return null;
        }
//        param.put("env_version","develop");//正式版为 "release"，体验版为 "trial"，开发版为 "develop"
//        param.put("check_path",false);
        //System.out.println(pro_env);
        if(DicConstants.SYS_Y.getCode().equals(pro_env)){
            System.out.println("正式");
            //正式环境
            param.put("env_version","release");//正式版为 "release"，体验版为 "trial"，开发版为 "develop"
        }else{
            System.out.println("体验");
            //测试参数，体验版使用，不要在正式使用
            param.put("env_version","trial");//正式版为 "release"，体验版为 "trial"，开发版为 "develop"
            param.put("check_path",false);
        }
        String codeName=storeUserId+"_commission_"+ IdUtils.fastUUID();
        String xml = JSONObject.toJSONString(param);
        String requestUrl= ConstantWeChat.GET_WX_ACODE_UNLIMIT.replace("#ACCESS_TOKEN#", tokenUtil.getToken(APPKEY).getAccessToken());
        JSONObject resultR= commonUtil.doPostFile(requestUrl,xml,codeName,requrl);
        if(resultR.containsKey("imgUrl")){
            String imgUrl=resultR.getString("imgUrl");
            String fileAbsolutePath=resultR.getString("fileAbsolutePath");

            Staff updateStaff = new Staff();
            updateStaff.setId(storeUserId);
            updateStaff.setBelowImageLocal(fileAbsolutePath);
            updateStaff.setBelowImageUrl(imgUrl);
            updateStaff.setBelowPage(qrcodePage);
            staffService.updateStaff(updateStaff);
            return imgUrl;
        }
        return null;
    }


    @PostMapping("/edit")
    @ApiOperation("修改员工")
    public AjaxResult edit(@ApiParam @RequestBody Staff staff){
        StoreUserRole role = getStoreUserRole();
        if(role == null){
            throw new CustomException("权限不足");
        }
        if(StringUtils.isEmpty(staff.getPhone()))
        {
            throw new CustomException("手机号必填");
        }
        Staff staff1=new Staff();
        staff1.setPhone(staff.getPhone());
        List<Staff> list=staffService.selectStaffList(staff1);
        if(list.size()>0) {
            throw new CustomException("手机号" + staff.getPhone() + "已存在");
        }
        staff.setStoreId(role.getStoreId());
        staff.setState(DicConstants.SYS_Y.getCode());
        staff.setUpdateBy(getLoginStoreUserId());
        staff.setUpdateType(DicConstants.BUSINESS_Business.getCode());
        staff.setPassword(SecurityUtils.encryptPassword(staff.getPassword()));
//        必须通过id修改
        return AjaxResult.success(staffService.updateStaff(staff));
    }



    @GetMapping("/del/{staffId}")
    @ApiOperation("删除员工")
    public AjaxResult del (@PathVariable Long staffId){
        StoreUserRole role = getStoreUserRole();
        if(role == null){
            throw new CustomException("权限不足!");
        }
//        判断是否是本店铺的员工
        Long storeId= role.getStoreId();
        System.out.println("ttdd");
        System.out.println(storeId);
        Long[] longs = new Long[1];
        longs[0] = staffId;
        Staff staff= staffService.selectStaffById(staffId);
        if(!(storeId.equals(staff.getStoreId())) ){
            throw new CustomException("权限不足!!");
        }
        return AjaxResult.success(staffService.logicDeleteStaff(longs,DicConstants.BUSINESS_Business.getCode(),role.getId()));
    }



    @GetMapping("/getOne/{staffId}")
    @ApiOperation("获取员工")
    public AjaxResult getOne (@PathVariable Long staffId){
        StoreUserRole role = getStoreUserRole();
        if(role == null){
            throw new CustomException("权限不足");
        }
        Long storeId= role.getStoreId();
        Long[] longs = new Long[1];
        longs[0] = staffId;
        Staff staff= staffService.selectStaffById(staffId);
        if(!(storeId.equals(staff.getStoreId())) ){
            throw new CustomException("权限不足!!");
        }
        Staff staff1=staffService.selectStaffById(staffId);
        ClerkBalanceRecord clerkBalanceRecord = new ClerkBalanceRecord();
        clerkBalanceRecord.setBusType("div");
        staff1.setMasterList(staffService.selectMasterListById(staff1.getId()));
        staff1.setDiscipleList(staffService.selectDiscipleListById(staff1.getId()));
        staff1.setSubordinateList(staffService.selectSubordinateListById(staff1.getId()));
        ClerkBalance clerkBalance = clerkBalanceService.selectClerkBalanceByStoreUserId(staff1.getId());
        staff1.setTotalAmount(clerkBalance.getCommission());
        clerkBalanceRecord.setStoreUserId(staff1.getId());
        List<ClerkBalanceRecord> ClerkBalanceRecordList = clerkBalanceRecordService.selectClerkBalanceRecordList(clerkBalanceRecord);
        staff1.setOrderCount(ClerkBalanceRecordList.size());
        return AjaxResult.success(staff1);
    }

    /**
     * 查询员工信息列表
     */
    @ApiOperation(value = "查询员工信息列表，涉及多分类，建议不分页")
    @GetMapping("/getList")
    public TableDataInfo list(Staff staff) {
        StoreUserRole role = getStoreUserRole();
        if (role == null) {
            throw new CustomException("权限不足");
        }
        StoreUserRole storeUserRole = getStoreUserRole();
        Staff staffParam = new Staff();
        staffParam.setStoreId(storeUserRole.getStoreId());
        startPage();
            List<Staff> result = staffService.selectStaffList(staffParam);
            ClerkBalanceRecord clerkBalanceRecord = new ClerkBalanceRecord();
            clerkBalanceRecord.setBusType("div");
            for (Staff staff1 : result) {
                staff1.setMasterList(staffService.selectMasterListById(staff1.getId()));
                staff1.setDiscipleList(staffService.selectDiscipleListById(staff1.getId()));
                staff1.setSubordinateList(staffService.selectSubordinateListById(staff1.getId()));
                ClerkBalance clerkBalance = clerkBalanceService.selectClerkBalanceByStoreUserId(staff1.getId());
                System.out.println("dd");
                System.out.println(clerkBalance);
                System.out.println(clerkBalance.getCommission());
                if(clerkBalance.getCommission() == null){
                    staff1.setTotalAmount(BigDecimal.ZERO);
                }else{
                    staff1.setTotalAmount(clerkBalance.getCommission());
                }

                clerkBalanceRecord.setStoreUserId(staff1.getId());
                List<ClerkBalanceRecord> ClerkBalanceRecordList = clerkBalanceRecordService.selectClerkBalanceRecordList(clerkBalanceRecord);
                staff1.setOrderCount(ClerkBalanceRecordList.size());
            }
            TableDataInfo tableDataInfo = getDataTable(result);
            return tableDataInfo;
        }

    /**
     * 某个staff的佣金详情
     */
    @GetMapping("/getStaffClerkBalanceRecord/{staffId}")
    public TableDataInfo getStaffClerkBalanceRecord(@PathVariable Long staffId)
    {
        ClerkBalanceRecord clerkBalanceRecord3 = new ClerkBalanceRecord();
        clerkBalanceRecord3.setStoreUserId(staffId);
        List<ClerkBalanceRecord> clerkBalanceRecordListAll = clerkBalanceRecordService.selectClerkBalanceRecordList(clerkBalanceRecord3);
        TableDataInfo tableDataInfo =getDataTable(clerkBalanceRecordListAll);
        return tableDataInfo;
    }
}
